import base64
import hashlib
import json
import time
import uuid

import requests

host = 'https://ai-vpr.hivoice.cn'
appkey = "*******我的appkey************"
secret = '*******我的secret************'
groupId = '***************************'
groupInfo = '****我的Python声纹组信息***'
# 需要对比的声纹id
featureId = '**************************'
featureInfo = '*******我的声纹信息描述********'
createGroupEndPoint = '/vpr/v1/createGroup'
createFeatureEndPoint = '/vpr/v1/createFeature'
confirmFeatureEndPoint = '/vpr/v1/confirmFeature'
identifyFeatureByGroupIdEndPoint = '/vpr/v1/identifyFeatureByGroupId'
identifyFeatureByIdsEndPoint = '/vpr/v1/identifyFeatureByIds'
updateFeatureByIdEndPoint = '/vpr/v1/updateFeatureById'
delFeatureByIdEndPoint = '/vpr/v1/delFeatureById'
delGroupByIdEndPoint = '/vpr/v1/delGroupById'
findFeatureListByGroupIdEndPoint = '/vpr/v1/findFeatureListByGroupId'
#需要辨认的音频文件名, 将需要辨认的声纹音频放到项目目录下, 文件名自行定义|修改
confirmFeatureFileName = 'confirmFeature.mp3'
#需要创建的音频文件名, 将需要辨认的声纹音频放到项目目录下, 文件名自行定义|修改
createFeatureFileName = 'createFeature.mp3'
class Client:
    def findFeatureListByGroupId(self):
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        find_feature_list_by_group_id_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
        }
        print('find_feature_list_by_group_id_param', find_feature_list_by_group_id_param)
        find_feature_list_by_group_id_resp = requests.post(url=host + findFeatureListByGroupIdEndPoint,
                                                           data=json.dumps(find_feature_list_by_group_id_param),
                                                           headers=headers)
        find_feature_list_by_group_id_result = json.loads(find_feature_list_by_group_id_resp.content)
        print('find_feature_list_by_group_id_result', find_feature_list_by_group_id_result)
        print('------------------------------------------------------------')

    # 删除声纹组
    def delGroupById(self):
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        del_group_by_id_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
        }
        print('del_group_by_id_param', del_group_by_id_param)
        del_group_by_id_resp = requests.post(url=host + delGroupByIdEndPoint,
                                             data=json.dumps(del_group_by_id_param),
                                             headers=headers)
        del_group_by_id_result = json.loads(del_group_by_id_resp.content)
        print('del_group_by_id_result', del_group_by_id_result)
        print('------------------------------------------------------------')

    # 删除声纹
    def delFeatureById(self):
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        del_feature_by_id_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "featureId": featureId
        }
        print('del_feature_by_id_param', del_feature_by_id_param)
        del_feature_by_id_resp = requests.post(url=host + delFeatureByIdEndPoint,
                                               data=json.dumps(del_feature_by_id_param),
                                               headers=headers)
        del_feature_by_id_result = json.loads(del_feature_by_id_resp.content)
        print('del_feature_by_id_result', del_feature_by_id_result)
        print('------------------------------------------------------------')

    # 修改声纹
    def updateFeatureById(self):
        update_feature = open(confirmFeatureFileName, 'rb').read()
        # 声纹base64字符串
        audio_data = base64.b64encode(update_feature)
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        update_feature_by_id_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "featureId": featureId,
            "featureInfo": '修改后的声纹',
            "audioData": audio_data.decode(),
            "audioSampleRate": 16000,
            "audioFormat": "mp3"
        }
        #print('update_feature_by_id_param', update_feature_by_id_param)
        update_feature_by_id_resp = requests.post(url=host + updateFeatureByIdEndPoint,
                                                  data=json.dumps(update_feature_by_id_param),
                                                  headers=headers)
        update_feature_by_id_result = json.loads(update_feature_by_id_resp.content)
        print('update_feature_by_id_result', update_feature_by_id_result)
        print('------------------------------------------------------------')

    # 声纹确认 1:N 不同组的多个声纹  将需要辨认的声纹音频放到resource目录下, 文件名自行定义, 获取方式自行修改
    def identifyFeatureByIds(self):
        identify_feature = open(createFeatureFileName, 'rb').read()
        # 声纹base64字符串
        audio_data = base64.b64encode(identify_feature)
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        feature_list = [{'groupId': groupId, "featureId": featureId}, {'groupId': groupId, "featureId": featureId}]
        identify_feature_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "featureList": feature_list,
            "topN": 1,
            "audioData": audio_data.decode(),
            "audioSampleRate": 16000,
            "audioFormat": "mp3"
        }
        #print('identify_feature_param', identify_feature_param)
        identify_feature_resp = requests.post(url=host + identifyFeatureByIdsEndPoint,
                                              data=json.dumps(identify_feature_param),
                                              headers=headers)
        identify_feature_result = json.loads(identify_feature_resp.content)
        print('identify_feature_result', identify_feature_result)
        print('------------------------------------------------------------')

    # 声纹辨认【1:N】组内所有声纹作对比 将需要辨认的声纹音频放到项目目录下, 文件名自行定义, 获取方式自行修改
    def identifyFeatureByGroupId(self):
        identify_feature = open(confirmFeatureFileName, 'rb').read()
        # 声纹base64字符串
        audio_data = base64.b64encode(identify_feature)
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        identify_feature_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "topN": 1,
            "audioData": audio_data.decode(),
            "audioSampleRate": 16000,
            "audioFormat": "mp3"
        }
        #print('identify_feature_param', identify_feature_param)
        identify_feature_resp = requests.post(url=host + identifyFeatureByGroupIdEndPoint,
                                              data=json.dumps(identify_feature_param),
                                              headers=headers)
        identify_feature_result = json.loads(identify_feature_resp.content)
        print('identify_feature_result', identify_feature_result)
        print('------------------------------------------------------------')

    # 声纹确认【1:1】   将需要辨认的声纹音频放到项目目录下, 文件名自行定义, 获取方式自行修改
    def confirmFeature(self):
        confirm_feature = open(confirmFeatureFileName, 'rb').read()
        # 声纹base64字符串
        audio_data = base64.b64encode(confirm_feature)
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        confirm_feature_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "featureId": featureId,
            "audioData": audio_data.decode(),
            "audioSampleRate": 16000,
            "audioFormat": "mp3"
        }
        #print('confirm_feature_param', confirm_feature_param)
        confirm_feature_resp = requests.post(url=host + confirmFeatureEndPoint, data=json.dumps(confirm_feature_param),
                                             headers=headers)
        confirm_feature_result = json.loads(confirm_feature_resp.content)
        print('confirm_feature_result', confirm_feature_result)
        print('------------------------------------------------------------')

    # 创建声纹 将声纹音频放到项目目录下, 文件名自行定义, 获取方式自行修改
    def createFeature(self):
        create_feature = open(createFeatureFileName, 'rb').read()
        # 声纹base64字符串
        audio_data = base64.b64encode(create_feature)
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        create_feature_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "featureId": featureId,
            "featureInfo": featureInfo,
            "audioData": audio_data.decode(),
            "audioSampleRate": 16000,
            "audioFormat": "mp3"
        }
        #print('create_feature_param', create_feature_param)
        create_feature_resp = requests.post(url=host + createFeatureEndPoint, data=json.dumps(create_feature_param),
                                            headers=headers)
        create_feature_result = json.loads(create_feature_resp.content)
        print('create_feature_result', create_feature_result)
        print('------------------------------------------------------------')

    def createGroup(self):
        timestamp = str(int(time.time() * 1000))
        nonce = str(uuid.uuid1()).replace('-', '')
        sign = self.getSign(timestamp, nonce)
        headers = {"Content-Type": "application/json"}
        creat_group_param = {
            "appkey": appkey,
            "timestamp": timestamp,
            "nonce": nonce,
            "sign": sign,
            "groupId": groupId,
            "groupInfo": groupInfo
        }
        print('creat_group_param', creat_group_param)
        creat_group_resp = requests.post(url=host + createGroupEndPoint, data=json.dumps(creat_group_param),
                                         headers=headers)
        creat_group_result = json.loads(creat_group_resp.content)
        print('creat_group_result', creat_group_result)
        print('------------------------------------------------------------')

    @staticmethod
    def getSign(timestamp, nonce):
        hs = hashlib.sha256()
        hs.update((appkey + timestamp + secret + nonce).encode('utf-8'))
        signature = hs.hexdigest().upper()
        return signature
###################################################
if __name__ == '__main__':
    client = Client()
    client.createGroup()
    client.createFeature()
    client.confirmFeature()
    client.identifyFeatureByGroupId()
    client.identifyFeatureByIds()
    client.findFeatureListByGroupId()
    client.updateFeatureById()
    client.delFeatureById()
    client.delGroupById()
